package com.ruoyi.system.listener;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ruoyi.common.constant.DeptConstants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.excel.ExcelListener;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.service.ISysDeptService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * 系统用户自定义导入
 *
 * @author Lion Li
 */
@Slf4j
public class SysDeptImportListener extends AnalysisEventListener<Map<Integer, String>> implements ExcelListener<Map<Integer, String>> {

    private final ISysDeptService deptService;
    private final boolean doUpdate;

    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public SysDeptImportListener(ISysDeptService deptService, String type, boolean updateSupport) {
        this.deptService = deptService;
        this.doUpdate = updateSupport;
    }

    @Override
    public void invoke(Map<Integer, String> readMap, AnalysisContext context) {
        String deptCode = readMap.get(1);
        SysDept dept = new SysDept();
        try {
            dept = deptService.selectDeptByCode(deptCode);
            // 验证是否存在这个部门
            if (ObjectUtil.isNull(dept)) {
                dept = new SysDept();
                setDeptValue(dept, readMap);
                deptService.insertDept(dept);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、账号 ").append(dept.getDeptName()).append(" 导入成功");
            } else if (this.doUpdate) {
                setDeptValue(dept, readMap);
                deptService.updateDept(dept);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、账号 ").append(dept.getDeptName()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、账号 ").append(dept.getDeptName()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、单位 " + dept.getDeptName() + "[" + deptCode + " ]导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //DO NOTHING
    }

    @Override
    public ExcelResult<Map<Integer, String>> getExcelResult() {
        return new ExcelResult<Map<Integer, String>>() {
            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<Map<Integer, String>> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }


    private void setDeptValue(SysDept dept, Map<Integer, String> dataMap) {
        String deptCode = dataMap.get(1);
        dept.setCode(deptCode);
        dept.setStatus(UserConstants.DEPT_NORMAL);
        dept.setDeptName(dataMap.get(2));
        dept.setShortName(dataMap.get(3));
        String parentCode = dataMap.get(4);
        if (StrUtil.isNotBlank(parentCode)) {
            SysDept parentDept = deptService.selectDeptByCode(parentCode);
            if (ObjectUtil.isNull(parentDept)) {
                throw new ServiceException("父级单位不存在");
            } else {
                dept.setParentId(parentDept.getDeptId());
            }
        }

        String gradeStr = dataMap.get(6);
        if (StrUtil.isNotBlank(gradeStr)) {
            dept.setGrade(gradeStr.split("-")[0]);
        }
        String classify = dataMap.get(7);
        if (StrUtil.isNotBlank(classify)) {
            dept.setClassify(classify.split("\\[")[0]);
        } else {
            if (StrUtil.isBlank(parentCode)) {
                dept.setType(DeptConstants.DEPT_TYPE_ORGANIZATION);
            }
            dept.setType(DeptConstants.DEPT_TYPE_UNIT);
        }
    }
}
